package com.vagavaga.bizworld.jpatx;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import javax.persistence.EntityTransaction;

class ChildTransaction extends EntityTransactionInterceptor {
    private final EntityTransaction tx;

    private ChildTransaction(EntityTransaction tx) {
        this.tx = tx;
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if (BEGIN.equals(method)) {
            if (tx.isActive()) return null;
            throw new IllegalStateException("Parent transaction not started!"); 
        }

        if (COMMIT.equals(method)) {
            return null;
        }

        if (ROLLBACK.equals(method)) {
            tx.setRollbackOnly();
            return null;
        }

        try {
            return method.invoke(tx, args);
        } catch (InvocationTargetException ite) {
            throw ite.getTargetException();
        }
    }

    public static EntityTransaction wrap(EntityTransaction tx) {
        ChildTransaction ct = new ChildTransaction(tx);
        return (EntityTransaction) Proxy.newProxyInstance(
                tx.getClass().getClassLoader(),
                new Class<?>[] { EntityTransaction.class },
                ct);
    }
}
